package com.erp.collect.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.collect.domain.ErpCollectProductDistributeLog;
import com.erp.collect.domain.bo.ErpCollectProductBBo;
import com.erp.collect.domain.vo.ErpCollectProductBVo;
import com.erp.collect.mapper.*;
import com.erp.collect.service.IErpCollectProductBService;
import com.ruoyi.collect.api.domain.*;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.dto.ComputeFreightDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 采集商品a 从1688采集 由complianceAe方法放入Service业务层处理
 *
 * @author erp
 * @date 2024-05-22
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductBServiceImpl implements IErpCollectProductBService {

    private final ErpCollectProductBMapper baseMapper;
    private final ErpCollectProductExpandBMapper erpCollectProductExpandBMapper;
    private final ErpCollectProductSkuBMapper erpCollectProductSkuBMapper;
    private final ErpCollectProductDistributeLogMapper erpCollectProductDistributeLogMapper;

    /**
     * 查询采集商品a 从1688采集 由complianceAe方法放入
     */
    @Override
    public ErpCollectProductBVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询采集商品a 从1688采集 由complianceAe方法放入列表
     */
    @Override
    public TableDataInfo<ErpCollectProductBVo> queryPageList(ErpCollectProductBBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpCollectProductB> lqw = buildQueryWrapper(bo);
        Page<ErpCollectProductBVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采集商品a 从1688采集 由complianceAe方法放入列表
     */
    @Override
    public List<ErpCollectProductBVo> queryList(ErpCollectProductBBo bo) {
        LambdaQueryWrapper<ErpCollectProductB> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpCollectProductB> buildQueryWrapper(ErpCollectProductBBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpCollectProductB> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCategoryId() != null, ErpCollectProductB::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpCollectProductB::getImageURLs, bo.getImageURLs());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), ErpCollectProductB::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpCollectProductB::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpCollectProductB::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpCollectProductB::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpCollectProductB::getCollectProductPrice, bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpCollectProductB::getProductPrice, bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpCollectProductB::getMobileDetail, bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpCollectProductB::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpCollectProductB::getPackageWidth, bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpCollectProductB::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpCollectProductB::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpCollectProductB::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpCollectProductB::getCustomAttributes, bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpCollectProductB::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpCollectProductB::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpCollectProductB::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpCollectProductB::getModeSizeChartList, bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpCollectProductB::getCollectUrl, bo.getCollectUrl());
        lqw.eq(bo.getCollectUserId() != null, ErpCollectProductB::getCollectUserId, bo.getCollectUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOldDetailImg()), ErpCollectProductB::getOldDetailImg, bo.getOldDetailImg());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpCollectProductB::getRevision, bo.getRevision());
        lqw.eq(StringUtils.isNotBlank(bo.getOperateType()), ErpCollectProductB::getOperateType, bo.getOperateType());
        return lqw;
    }

    /**
     * 新增采集商品a 从1688采集 由complianceAe方法放入
     */
    @Override
    public Boolean insertByBo(ErpCollectProductBBo bo) {
        ErpCollectProductB add = BeanUtil.toBean(bo, ErpCollectProductB.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采集商品a 从1688采集 由complianceAe方法放入
     */
    @Override
    public Boolean updateByBo(ErpCollectProductBBo bo) {
        ErpCollectProductB update = BeanUtil.toBean(bo, ErpCollectProductB.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProductB entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采集商品a 从1688采集 由complianceAe方法放入
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<Object> getCollectProductBAllInfoById(Long collectProductId) {
        ComputeFreightDto dto = new ComputeFreightDto();
        ErpCollectProductB collectProductA = baseMapper.selectById(collectProductId);
        ErpCollectProductExpandB collectProductExpandA = erpCollectProductExpandBMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductExpandB>().eq(ErpCollectProductExpandB::getCollectProductId, collectProductId)
        );
        List<ErpCollectProductSkuB> skuAList = erpCollectProductSkuBMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSkuB>().eq(ErpCollectProductSkuB::getCollectProductId, collectProductId)
        );
        dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(collectProductA)));
        dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(collectProductExpandA)));
        dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuAList)));
        return R.ok(dto);
    }


    @Override
    public R<Object> sendCollectUpdateResult(Long collectProductId, Integer type, String msg) {
        try {
            List<ErpCollectProductDistributeLog> logList = erpCollectProductDistributeLogMapper.selectList(
                    new LambdaQueryWrapper<ErpCollectProductDistributeLog>().eq(ErpCollectProductDistributeLog::getCollectProductId, collectProductId)
            );
            if (type == 1) {
                //标记erp_collect_product_distribute_log 测试发布成功 结果
                logList.forEach(log -> {
                            log.setDistributeAe("3");
                            log.setAeLog(msg);
                        }
                );
            } else {
                //标记erp_collect_product_distribute_log 测试发布失败
                //记录原因到erp_collect_product_distribute_log表
                logList.forEach(log -> {
                            log.setDistributeAe("2");
                            log.setAeLog(msg);
                        }
                );
                //删除erp_collect_product_a 三表中对应数据
                erpCollectProductSkuBMapper.delete(new LambdaQueryWrapper<ErpCollectProductSkuB>().eq(ErpCollectProductSkuB::getCollectProductId,collectProductId));
                erpCollectProductExpandBMapper.delete(new LambdaQueryWrapper<ErpCollectProductExpandB>().eq(ErpCollectProductExpandB::getCollectProductId,collectProductId));
                baseMapper.delete(new LambdaQueryWrapper<ErpCollectProductB>().eq(ErpCollectProductB::getId,collectProductId));
            }
            erpCollectProductDistributeLogMapper.updateBatchById(logList);
        }catch (Exception e){
            return R.fail("标记失败");
        }
        return R.ok("标记成功");

    }
}
